<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class BubbleSort extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'bubblesort';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Please input the arguemnt tobe sorted. Press Q to Quit');
        $numbers = [];

        $number = $this->ask('Your number');
        for (;is_numeric($number);){
            array_push($numbers, $number);
            $number = $this->ask('Your number');
        }

        $this->info(json_encode($numbers, JSON_UNESCAPED_UNICODE));
        $result = $this->bubblesort($numbers);

        $this->info(json_encode($result, JSON_UNESCAPED_UNICODE));
        return Command::SUCCESS;
    }

    private function bubblesort($arr){
        $length = count($arr);

        for ($i = 0; $i < $length - 1; $i++) {
            for ($j = 0; $j < $length - 1 - $i; $j++) {
                if ($arr[$j] > $arr[$j + 1]) {
                    $tmp         = $arr[$j];
                    $arr[$j]     = $arr[$j + 1];
                    $arr[$j + 1] = $tmp;
                }
            }
        }

        return $arr;

    }

}
